Skip to content

Exercises

A Slider component

In the sandbox below, you'll see that we've built a Slider component.

Internally, this component renders an <input type="range">, the built-in DOM node for creating ranges and sliders. And so we can think of this Slider component as a “supercharged” range input.

Unfortunately, we've only exposed a subset of the attributes we might wish to set on this DOM node through props. Your mission is to forward all props onto the input, so that we can treat <Slider> as a supercharged range input.

Acceptance Criteria:

  • The Slider component should use the prop delegation technique to forward all unspecified props to the <input type="range"> that it renders.

Code Playground

import React from 'react';

import styles from './Slider.module.css';

function Slider({ label, min, max, value, onChange }) {
const id = React.useId();
return (
<div className={styles.wrapper}>
<label
htmlFor={id}
className={styles.label}
>
{label}
</label>
<input
type="range"
id={id}
className={styles.slider}
min={min}
max={max}
value={value}
onChange={onChange}
/>
</div>
);
}

export default Slider;

Solution:

Note: In addition to sharing my solution, I also dig into the implementation of this Slider component a bit in the video above. If you're not familiar with <input type="range">, I suggest checking it out!

You can learn more about range inputs on MDN.

A Toggle component

Toggle components are similar to checkboxes. They're often used to flip a value on or off.

In this exercise, we have a custom <Toggle> component. It looks like this:

We want to be able to pass a custom className to provide custom styles. For example, maybe we want to pass a CSS class that updates the color of the toggle circle:

Screenshot showing a toggle being checked/unchecked, but with a green hue, labeled “Low Power Mode”

Your mission is to update the Toggle component so that it can be customized, by passing a className. It should also support additional custom props, like data attributes.

Acceptance Criteria:

  • In the example below, the second <Toggle> instance has a prop: className="green-toggle". This class should be applied to the <button> inside the Toggle component, producing the green circle shown in the GIF above.
  • Other props (eg. data attributes) should also be forwarded along to the <button> element.

Note: It may be helpful to review the Conflicts section 👀 of the Rest/Spread primer lesson.

Code Playground

import React from 'react';

import useToggle from './hooks/use-toggle';
import Toggle from './Toggle';

function App() {
const [enableWifi, toggleEnableWifi] = useToggle(true);
const [lowPowerMode, toggleLowPowerMode] = useToggle(false);
return (
<main>
<Toggle
label="Enable Wi-Fi"
checked={enableWifi}
onClick={toggleEnableWifi}
/>
<Toggle
className="green-toggle"
label="Low Power Mode"
checked={lowPowerMode}
onClick={toggleLowPowerMode}
/>
</main>
);
}

export default App;

Solution: